<template>
  <q-page class="q-pa-md">

    <q-form class="q-pa-md" @submit.prevent="uploadFileGuanglan" @reset.prevent="resetForm">

      <div class="q-gutter-sm q-mb-md">
        <q-card flat>
          <q-card-section class="row items-center">
            <div class="col-auto">
              <q-icon name="mdi-cable-data" color="primary" />
            </div>

          </q-card-section>
        </q-card>
      </div>
      <div class="col">
        <q-file dense filled v-model="selectedFile" label="选择核验后的excel文件" @change="handleFileUpload" class="q-mt-md" />
      </div>
      <div class="q-mt-md q-gutter-sm">
        <q-btn dense rounded type="submit" color="primary" icon="cloud_upload" label="导入数据湖" />
        <q-btn dense rounded type="reset" color="secondary" label="重置" />
      </div>

    </q-form>
    <q-separator />

    <!-- 上传组件显示 -->
    <!--    <q-form class="q-pa-md" @submit.prevent="uploadFile" @reset.prevent="resetForm">-->
    <!--      <q-input dense filled v-model="inputContent" label="输入内容进行搜索..." @input="showRecommendations = true"></q-input>-->

    <!--      <q-list v-if="showRecommendations && filteredGuanglus.length">-->
    <!--        <q-item v-for="(guanglu, index) in filteredGuanglus" :key="index" clickable @click="selectGuanglu(guanglu)" class="q-mb-xs">-->
    <!--          <q-item-section>{{ guanglu }}</q-item-section>-->
    <!--        </q-item>-->
    <!--      </q-list>-->

    <!--      <q-file dense filled v-model="selectedFile" label="选择文件" @change="handleFileUpload" class="q-mt-md"></q-file>-->

    <!--      <div class="q-mt-md q-gutter-sm">-->
    <!--        <q-btn dense rounded type="submit" color="primary" icon="cloud_upload" label="导入全文检索"></q-btn>-->
    <!--        <q-btn dense rounded type="reset" color="secondary" label="重置"></q-btn>-->
    <!--      </div>-->

    <!--      <q-chip v-if="uploadFileName" outline color="primary" class="q-mt-md custom-chip">-->
    <!--        <div class="wenjianming">-->
    <!--        待导入光路文件名：{{ uploadFileName + '.xlsx' }}-->
    <!--        </div>-->
    <!--      </q-chip>-->
    <!--    </q-form>-->

    <!-- 搜索组件显示 -->
    <div class="q-pa-md">
      <div class="q-pa-md row q-gutter-x-md">
        <div class="col">
          <q-select
            v-model="selectedColumns"
            multiple
            :options=columns
            label="选择要显示的列"
          />
        </div>
        <!--        <div class="col">-->
        <!--          <q-input dense filled v-model="searchQuery" label="输入搜索内容..."></q-input>-->
        <!--        </div>-->
        <!--        <div class="col-auto">-->

        <!--          <q-btn dense rounded color="primary" icon="search" label="搜索" @click="searchData"></q-btn>-->
        <!--        </div>-->
        <!--        <div class="col">-->
        <!--          <q-input dense filled v-model="searchQuery" label="输入搜索内容..."></q-input>-->
        <!--        </div>-->
        <!--        <div class="col-auto">-->

        <!--          <q-btn dense rounded color="primary" icon="search" label="搜索" @click="searchData"></q-btn>-->
        <!--        </div>-->
      </div>
      <q-btn label="Export to Excel" color="primary" @click="exportToExcel" />

      <q-table :data="querySearchResult" :columns="filteredColumns" flat binary-state-sort class="q-mt-md"></q-table>

    </div>


    <!-- 其他组件内容省略 -->
  </q-page>
</template>

<script>
import * as XLSX from 'xlsx';
export default {
  name: 'EsImport',

  data() {
    return {
      selectedColumns: [], // 用户选择显示的列名数组


      columns: [
      ],
      searchQuery: '',
      searchResults: [],
      activeComponent: 'upload',
      currentPage: '当前光路上传',
      inputContent: '',
      uniqueGuanglus: [],
      showRecommendations: true,
      selectedFile: null,
      uploadFileName: '',
      querySearchResult:[],

    };
  },

  computed: {
    filteredColumns() {
      return this.selectedColumns;
    },
    filteredSearchResults() {
      return this.searchResults;

    },
    filteredGuanglus() {
      return this.showRecommendations && this.inputContent !== '' ? this.uniqueGuanglus.filter(item =>
        item.toLowerCase().includes(this.inputContent.toLowerCase())
      ) : [];
    }
  },

  methods: {
    exportToExcel() {
      const data = this.querySearchResult.map(row => {
        const rowData = {};
        this.filteredColumns.forEach(column => {
          rowData[column.label] = row[column.field];
        });
        return rowData;
      });

      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Results");
      XLSX.writeFile(wb, "export.xlsx");
    },
    searchData() {
      this.querySearchResult = this.filteredSearchResults;
    },
    setActiveComponent(componentName) {
      this.activeComponent = componentName;
    },
    setActivePage(pageName) {
      this.currentPage = pageName; // 设置当前激活的页面
      // 在这里可以根据pageName来加载数据或进行其他操作
      // 例如：this.loadDataForPage(pageName);
    },
    setUniqueGuanglus(data) {
      this.uniqueGuanglus = data;
    },

    selectGuanglu(guanglu) {
      this.inputContent = guanglu; // 更新输入框内容为选择的推荐项
      this.showRecommendations = false; // 隐藏推荐列表
      this.uploadFileName = guanglu; // 更新待上传的文件名为选择的推荐项

      this.searchQuery = guanglu
    },
    handleFileUpload(event) {
      this.selectedFile = event.target.files[0]; // 保存选中的文件
    },
    uploadFileGuanglan() {
      const formData = new FormData();
      formData.append('file', this.selectedFile, '评级文件.xlsx'); // 设置上传的文件名
      fetch('http://localhost:5000/pushhi', {
        method: 'POST',
        body: formData,
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          alert('文件上传成功！');
        })
        .catch(error => {
          console.error('Error uploading file:', error);
          alert('文件上传失败！');
        });
    },
    uploadFile() {
      if (!this.selectedFile || !this.uploadFileName) {
        alert('请选择文件并确保已选择推荐项作为文件名！');
        return;
      }
      // 27b5487d.r8.cpolar.top  http://1e7cbeba.r15.cpolar.top
      const formData = new FormData();
      formData.append('file', this.selectedFile, this.uploadFileName + '.xlsx'); // 设置上传的文件名
      fetch('http://1e7cbeba.r15.cpolar.top/upload', {
        method: 'POST',
        body: formData,
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          alert('文件上传成功！');
        })
        .catch(error => {
          console.error('Error uploading file:', error);
          alert('文件上传失败！');
        });
    }
  },

  mounted() {


    // 定义Elasticsearch查询
    var esQuery = {
      size: 0, // 不需要具体的文档内容，只需要聚合结果
      aggs: {
        unique_guanglu: {
          terms: {
            field: "对应光路.keyword",
            size: 10000 // 根据实际情况调整这个值以适应唯一值的数量
          }
        }
      }
    };
    // 此处调用API获取uniqueGuanglus数据并设置
    fetch('http://43.136.220.136:9002/xianmen_guanglu/_search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa('admin:1992A1573')
      },
      body: JSON.stringify(esQuery)
    })
      .then(response => response.json())
      .then(data => {
        const uniqueGuanglus = data.aggregations.unique_guanglu.buckets.map(bucket => bucket.key);
        this.setUniqueGuanglus(uniqueGuanglus); // 设置uniqueGuanglus数组
      })
      .catch(error => console.error('Error fetching data:', error));


    //    所有数据查询

    esQuery = {
      query: {
        match_all: {} // 匹配所有文档
      },
      size: 500 // 控制返回的文档数量，这里假设返回前10条文档
    };

    fetch('http://43.136.220.136:9002/sqlgen/_search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa('admin:1992A1573') // 认证信息
      },
      body: JSON.stringify(esQuery)
    })
      .then(response => response.json())
      .then(data => {
        // 处理搜索结果
        // data.hits.hits数组包含了匹配的文档，每个文档的_source属性包含了文档的字段
        this.searchResults = data.hits.hits.map(hit => hit._source);


        if (this.filteredSearchResults.length > 0) {
          this.columns = Object.keys(this.filteredSearchResults[0]).map(key => ({
            name: key,
            label: key, // 可以在这里将 key 转换为更友好的标签
            field: key,
            align: 'left',
            sortable: true
          }));
        }




        console.log(this.searchResults); // 输出或处理搜索结果
        this.querySearchResult = this.filteredSearchResults
        // this.selectedColumns = this.columns
        // 这里你可以将searchResults赋值给Vue实例的某个数据属性，用于在界面上显示
      })
      .catch(error => console.error('Error fetching data:', error));

  }
};
</script>

<style>
.q-pa-md {
  max-width: 800px;
  margin: 20px auto;
}

</style>
<style>
.custom-chip .wenjianming {
  width:100%;
  white-space: wrap;
  word-break: break-all; /* 允许在任何字符处断字换行 */
}

.custom-chip
{
  height: 200%;
}
.custom-input-bg .q-field__control {
  background-color: #f0f0f0; /* 你希望的背景颜色 */
}
</style>
